package com.ruoyi.controller;

import java.util.List;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.domain.dto.PenaltyDto;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.domain.Penalty;
import com.ruoyi.service.IPenaltyService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 罚款业务Controller
 *
 * @author qyb
 * @date 2023-12-26
 */
@RestController
@RequestMapping("/user/penalty")
public class PenaltyController extends BaseController
{
    @Autowired
    private IPenaltyService penaltyService;
    /**
     * 模糊查询，图书名，用户名，是否赔偿
     */
    @GetMapping("/searchList")
    public TableDataInfo searchList(PenaltyDto penaltyDto) {
        PenaltyDto pd=penaltyService.selectRoleIdByUserId(penaltyDto);
        List<PenaltyDto> list;
        startPage();
        if(pd.getRoleId()==2)//普通用户
        {
            penaltyDto.setUserId(pd.getUserId());
            penaltyDto.setRoleId(pd.getRoleId());
        }
        list = penaltyService.selectSearchList(penaltyDto);
        return getDataTable(list);
    }
    /**
     * 修改编辑罚款业务
     */
    @PreAuthorize("@ss.hasPermi('user:penalty:edit')")
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody @Validated Penalty penalty) {
        return toAjax(penaltyService.updatePenalty(penalty));
    }
    /**
     * 删除罚款业务
     */
    @PreAuthorize("@ss.hasPermi('user:penalty:remove')")
    @PostMapping("/remove")
    public AjaxResult remove(@RequestBody String penaltyIds) {
        JSONObject jsonObject = JSONObject.parseObject(penaltyIds);
        String str = jsonObject.get("penaltyIds").toString();
        String[] stringArray = str.split(","); // 使用逗号分隔字符串并生成字符串数组
        Long[] longArray = new Long[stringArray.length];
        for (int i = 0; i < stringArray.length; i++) {
            try {
                longArray[i] = Long.parseLong(stringArray[i].trim()); // 将每个字符串转换为 Long 类型
            } catch (NumberFormatException e) {
                // 处理无法转换为 Long 类型的情况
                e.printStackTrace();
                // 可以选择跳过该值、设置默认值，或者抛出异常等
            }
        }
        return toAjax(penaltyService.deletePenaltyByPenaltyIds(longArray));
    }
//    /**
//     * 新增罚款业务，用于测试mapper
//     */
//    @PostMapping("/insert")
//    public AjaxResult add(@RequestBody Penalty penalty) {
//        return toAjax(penaltyService.insertPenalty(penalty));
//    }
}
